from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_, and_
from typing import Optional
from datetime import datetime
from database import get_db
from models import Conversation
from schemas import ConversationResponse, ConversationListResponse
from utils.auth_utils import get_current_user
from logger import logging

router = APIRouter(prefix="/api/history", tags=["历史对话管理"])

# 导入chat_sessions用于清理内存缓存
from router.chat_router import chat_sessions


@router.get("/conversations", response_model=ConversationListResponse, summary="获取对话历史列表")
async def get_conversations(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回的记录数"),
    keyword: Optional[str] = Query(None, description="搜索关键词（标题、会话ID或消息内容）"),
    start_date: Optional[str] = Query(None, description="开始日期 (YYYY-MM-DD)"),
    end_date: Optional[str] = Query(None, description="结束日期 (YYYY-MM-DD)"),
    source: Optional[str] = Query(
        None, description="对话来源筛选：internal-内部聊天, external-外部聊天"),
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    """
    获取对话历史列表，支持分页和搜索过滤

    - **skip**: 跳过的记录数（用于分页）
    - **limit**: 返回的记录数（用于分页，最大100）
    - **keyword**: 搜索关键词，可以搜索标题、会话ID或消息内容
    - **start_date**: 开始日期，格式为YYYY-MM-DD
    - **end_date**: 结束日期，格式为YYYY-MM-DD
    - **source**: 对话来源筛选，可选值：internal（内部聊天）、external（外部聊天）
    """
    try:
        query = db.query(Conversation)

        # 关键词搜索（搜索标题、会话ID和消息内容）
        if keyword:
            keyword_filter = or_(
                Conversation.title.ilike(f"%{keyword}%"),
                Conversation.session_id.ilike(f"%{keyword}%"),
                Conversation.messages.cast(str).ilike(f"%{keyword}%")
            )
            query = query.filter(keyword_filter)

        # 来源筛选
        if source:
            if source in ["internal", "external"]:
                query = query.filter(Conversation.source == source)
            else:
                raise HTTPException(
                    status_code=400, detail="来源参数值错误，应为internal或external")

        # 日期范围过滤
        if start_date:
            try:
                start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
                query = query.filter(Conversation.updated_at >= start_datetime)
            except ValueError:
                raise HTTPException(
                    status_code=400, detail="开始日期格式错误，应为YYYY-MM-DD")

        if end_date:
            try:
                end_datetime = datetime.strptime(
                    f"{end_date} 23:59:59", "%Y-%m-%d %H:%M:%S")
                query = query.filter(Conversation.updated_at <= end_datetime)
            except ValueError:
                raise HTTPException(
                    status_code=400, detail="结束日期格式错误，应为YYYY-MM-DD")

        # 获取总记录数
        total = query.count()

        # 按更新时间降序排列，并进行分页
        conversations = query.order_by(
            Conversation.updated_at.desc()).offset(skip).limit(limit).all()

        logging.info(f"用户 {current_user.username} 查询对话历史列表，总计 {total} 条记录")

        return ConversationListResponse(
            total=total,
            conversations=conversations
        )
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"获取对话历史列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取对话历史列表失败: {str(e)}")


@router.get("/conversations/{conversation_id}", response_model=ConversationResponse, summary="获取对话历史详情")
async def get_conversation(
    conversation_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    """
    根据ID获取对话历史详情

    - **conversation_id**: 对话ID
    """
    try:
        conversation = db.query(Conversation).filter(
            Conversation.id == conversation_id).first()

        if not conversation:
            raise HTTPException(status_code=404, detail="对话历史不存在")

        logging.info(
            f"用户 {current_user.username} 查询对话详情，ID: {conversation_id}")

        return conversation
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"获取对话历史详情失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取对话历史详情失败: {str(e)}")


@router.delete("/conversations/{conversation_id}", summary="删除对话历史")
async def delete_conversation(
    conversation_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    """
    删除指定的对话历史记录

    - **conversation_id**: 对话ID
    """
    try:
        conversation = db.query(Conversation).filter(
            Conversation.id == conversation_id).first()

        if not conversation:
            raise HTTPException(status_code=404, detail="对话历史不存在")

        session_id = conversation.session_id
        title = conversation.title

        db.delete(conversation)
        db.commit()

        # 同时清理内存缓存
        if session_id in chat_sessions:
            del chat_sessions[session_id]
            logging.info(f"已清理内存中的会话缓存，session_id: {session_id}")

        logging.info(
            f"用户 {current_user.username} 删除对话历史，ID: {conversation_id}, 会话ID: {session_id}")

        return {
            "message": "对话历史删除成功",
            "session_id": session_id,
            "title": title
        }
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logging.error(f"删除对话历史失败: {e}")
        raise HTTPException(status_code=500, detail=f"删除对话历史失败: {str(e)}")
